package com.zs.myorm.framework.core.method.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.zs.myorm.framework.core.annotation.Colunm;
import com.zs.myorm.framework.core.annotation.Id;
import com.zs.myorm.framework.core.annotation.TableName;
import com.zs.myorm.framework.core.execute.ISqlExecute;
import com.zs.myorm.framework.core.method.IMethodHandler;

public class SaveMethodHandlerImpl implements IMethodHandler {
	private ISqlExecute sqlExecute;
	private final String methodName = "save";
	public String getMethodName() {
		return this.methodName ;
	}
	public void setSqlExecute(ISqlExecute sqlExecute) {
		this.sqlExecute = sqlExecute;
	}

	@Override
	public Object invoke(Class<?> beanClass, Method method, Object[] args) throws Exception{
			String tableName = null;
			List<String> ids = null;
			List<String> c = null;
			if (beanClass != null) {
				TableName annotation = beanClass.getAnnotation(TableName.class);
				tableName = annotation.value();
				Field[] declaredFields = beanClass.getDeclaredFields();
				ids = new ArrayList<String>();
				c = new ArrayList<String>();
				for (Field f : declaredFields) {
					Id id = f.getAnnotation(Id.class);
					if (id != null) {
						String value = id.value();
						if (value == null || value.isEmpty()) {
							value = f.getName();
						}
						ids.add(value);
					} else {
						Colunm col = f.getAnnotation(Colunm.class);
						if (col != null) {
							String value = col.value();
							if (value == null || value.isEmpty()) {
								value = f.getName();
							}
							c.add(value);
						}
					}
				}
			}
			
			
			
			String sql = "insert into " + tableName + " ( " + ids.get(0) + ",";
			for (String c0 : c) {
				sql += c0 + ",";
			}
			sql = sql.substring(0, sql.length() - 1);
			sql += ")values(?,?)";

			Object[] param = new Object[2];
			Field[] declaredFields = beanClass.getDeclaredFields();
			for (Field f : declaredFields) {
				Id id = f.getAnnotation(Id.class);
				String value = null;
				if (id != null) {
					value = id.value();
					if (value == null || value.isEmpty()) {
						value = f.getName();
					}
					f.setAccessible(true);
					Object va = f.get(args[0]);
					param[0] = va;
				} else {
					Colunm col = f.getAnnotation(Colunm.class);
					if (col != null) {
						value = col.value();
						if (value == null || value.isEmpty()) {
							value = f.getName();
						}
						c.add(value);
					}
					f.setAccessible(true);
					Object va = f.get(args[0]);
					param[1] = va;
				}

			}
			return this.sqlExecute.insert(sql, param);
		
	}

}
